package com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.excel.handler.ActiveFaultVerifyBaseHandler;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.repository.HddcB4SampleprojecttableNativeRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.repository.HddcB4SampleprojecttableRepository;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.repository.entity.HddcB4SampleprojecttableEntity;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.service.HddcB4SampleprojecttableService;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.viewobjects.HddcB4SampleprojecttablePageVO;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.viewobjects.HddcB4SampleprojecttableQueryParams;
import com.css.zfzx.sjcj.modules.hddcB4_SampleProjectTable.viewobjects.HddcB4SampleprojecttableVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 野外采样数据-采样工程表管理
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcB4SampleprojecttableServiceImpl implements HddcB4SampleprojecttableService {

    private final HddcB4SampleprojecttableRepository hddcB4SampleprojecttableRepository;
    private final HddcB4SampleprojecttableNativeRepository hddcB4SampleprojecttableNativeRepository;
    private final ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler;

    @Autowired
    public HddcB4SampleprojecttableServiceImpl(HddcB4SampleprojecttableRepository hddcB4SampleprojecttableRepository,
                                               HddcB4SampleprojecttableNativeRepository hddcB4SampleprojecttableNativeRepository,
                                               ActiveFaultVerifyBaseHandler activeFaultVerifyBaseHandler) {
        this.hddcB4SampleprojecttableRepository = hddcB4SampleprojecttableRepository;
        this.hddcB4SampleprojecttableNativeRepository = hddcB4SampleprojecttableNativeRepository;
        this.activeFaultVerifyBaseHandler = activeFaultVerifyBaseHandler;
    }

    @Override
    public JSONObject queryHddcB4Sampleprojecttables(HddcB4SampleprojecttableQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcB4SampleprojecttablePageVO> hddcB4SampleprojecttablePage = this.hddcB4SampleprojecttableNativeRepository.queryHddcB4Sampleprojecttables(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcB4SampleprojecttablePage);
    }

    @Override
    public HddcB4SampleprojecttableEntity getHddcB4Sampleprojecttable(String id) {
        return this.hddcB4SampleprojecttableRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampleprojecttableEntity saveHddcB4Sampleprojecttable(HddcB4SampleprojecttableEntity hddcB4Sampleprojecttable) {
        String uuid = UUIDGenerator.getUUID();
        hddcB4Sampleprojecttable.setUuid(uuid);
        hddcB4Sampleprojecttable.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcB4Sampleprojecttable.setCreateTime(now);
        hddcB4Sampleprojecttable.setUpdateTime(now);
        hddcB4Sampleprojecttable.setIsValid(PlatformConstants.Y);
        hddcB4Sampleprojecttable.setQualityinspectionStatus(PlatformConstants.N);
        hddcB4Sampleprojecttable.setExtends10(PlatformConstants.Y);
        this.hddcB4SampleprojecttableRepository.save(hddcB4Sampleprojecttable);
        return hddcB4Sampleprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcB4SampleprojecttableEntity updateHddcB4Sampleprojecttable(HddcB4SampleprojecttableEntity hddcB4Sampleprojecttable) {
        HddcB4SampleprojecttableEntity entity = hddcB4SampleprojecttableRepository.findById(hddcB4Sampleprojecttable.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcB4Sampleprojecttable);
        hddcB4Sampleprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcB4Sampleprojecttable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcB4SampleprojecttableRepository.save(hddcB4Sampleprojecttable);
        return hddcB4Sampleprojecttable;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcB4Sampleprojecttables(List<String> ids) {
        List<HddcB4SampleprojecttableEntity> hddcB4SampleprojecttableList = this.hddcB4SampleprojecttableRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcB4SampleprojecttableList) && hddcB4SampleprojecttableList.size() > 0) {
            for(HddcB4SampleprojecttableEntity hddcB4Sampleprojecttable : hddcB4SampleprojecttableList) {
//                this.hddcB4SampleprojecttableRepository.delete(hddcB4Sampleprojecttable);
                hddcB4Sampleprojecttable.setIsValid(PlatformConstants.N);
                hddcB4Sampleprojecttable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcB4Sampleprojecttable.setUpdateTime(new Date());
                this.hddcB4SampleprojecttableRepository.save(hddcB4Sampleprojecttable);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcB4SampleprojecttableQueryParams queryParams, HttpServletResponse response) {
        List<HddcB4SampleprojecttableEntity> yhDisasterEntities = hddcB4SampleprojecttableNativeRepository.exportYhDisasters(queryParams);
        List<HddcB4SampleprojecttableVO> list=new ArrayList<>();
        for (HddcB4SampleprojecttableEntity entity:yhDisasterEntities) {
            HddcB4SampleprojecttableVO yhDisasterVO=new HddcB4SampleprojecttableVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"采样工程表","采样工程表",HddcB4SampleprojecttableVO.class,"采样工程表.xls",response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(activeFaultVerifyBaseHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcB4SampleprojecttableVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcB4SampleprojecttableVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcB4SampleprojecttableVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcB4SampleprojecttableVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcB4SampleprojecttableVO> list) {
        for (HddcB4SampleprojecttableVO hddcB4SampleprojecttableVO : list) {
            HddcB4SampleprojecttableEntity yhDisasterEntity = new HddcB4SampleprojecttableEntity();
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcB4SampleprojecttableVO, yhDisasterEntity);
            saveHddcB4Sampleprojecttable(yhDisasterEntity);
        }
    }
    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcB4SampleprojecttableEntity> hddcDataList = this.hddcB4SampleprojecttableRepository.queryByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB4SampleprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB4SampleprojecttableRepository.save(entity);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcB4SampleprojecttableEntity> hddcDataList = this.hddcB4SampleprojecttableRepository.queryByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcDataList) && hddcDataList.size() > 0) {
            for(HddcB4SampleprojecttableEntity entity : hddcDataList) {
                entity.setUpdateUser(PlatformSessionUtils.getUserId());
                entity.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                entity.setIsValid(PlatformConstants.N);
                this.hddcB4SampleprojecttableRepository.save(entity);
            }
        }
    }

}
